package com.dbq.fast.business.coupons;

import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.os.Bundle;

import com.dbq.fast.R;
import com.dbq.fast.analysis.EventConstant;
import com.dbq.fast.analysis.YibaAnalysis;
import com.dbq.fast.business.coupons.bean.ContentBean;
import com.dbq.fast.business.coupons.bean.CouponsData;
import com.dbq.fast.business.coupons.bean.Page;
import com.dbq.fast.business.login.api.LoginApi;
import com.dbq.fast.business.product.api.CommonTransformer;
import com.dbq.fast.common.base.BaseActivity;
import com.dbq.fast.common.bean.User;
import com.dbq.fast.common.net.HttpManager;
import com.dbq.fast.common.net.RemoteApiCallBack;

import java.util.ArrayList;

public class CouponsActivity extends BaseActivity implements IOnRefreshCallback {
    private ViewPager viewPager;
    private TabLayout tabLayout;
    private String[] titles;

    private Page pageInfo;
    private User userInfo;
    private CouponsFragment cf0;
    private CouponsFragment cf1;
    private CouponsFragment cf2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_coupons);
        titles = new String[]{""/*getString(R.string.no_use)*/, ""/*getString(R.string.used)*/, ""/*getString(R.string.out_of_date)*/};
        viewPager = findViewById(R.id.viewPager);
        tabLayout = findViewById(R.id.tab_layout);

        userInfo = User.getInstance();
        initData(0, CouponsFragment.REFRESH);
        initListener();
        tabLayout.setTabMode(TabLayout.MODE_FIXED);
        //设置tabLayout文字选中和未选中效果
        tabLayout.setTabTextColors(getResources().getColor(R.color.other_info_black), getResources().getColor(R.color.other_info_black));
        //设置下划线颜色
        tabLayout.setSelectedTabIndicatorColor(getResources().getColor(R.color.pay_btn_purple));
        tabLayout.setupWithViewPager(viewPager);
        ArrayList<Fragment> list = new ArrayList<>();

        cf0 = CouponsFragment.newInstance(0);
        cf1 = CouponsFragment.newInstance(1);
        cf2 = CouponsFragment.newInstance(2);

        list.add(cf0);
        list.add(cf1);
        list.add(cf2);
        PagerAdapter pagerAdapter = new PagerAdapter(getSupportFragmentManager(), list, titles);
        viewPager.setAdapter(pagerAdapter);
        viewPager.setOffscreenPageLimit(2);

        //处理从分享页面中调整到该界面时，展示第二个界面
        String page = getIntent().getStringExtra("page");
        if ("1".equals(page)) {
            viewPager.setCurrentItem(1);
        }
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (position == 0) {
                    YibaAnalysis.getInstance().event(CouponsActivity.this, EventConstant.EVENT_CLICK_COUPON_UNUSED_PAGE);
                } else if (position == 1) {
                    YibaAnalysis.getInstance().event(CouponsActivity.this, EventConstant.EVENT_CLICK_COUPON_USED_PAGE);
                } else if (position == 1) {
                    YibaAnalysis.getInstance().event(CouponsActivity.this, EventConstant.EVENT_CLICK_COUPON_EXPIRED_PAGE);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    private void initData(int pageId, int refreshStatus) {
        pageInfo = new Page();
        pageInfo.page = pageId;
        HttpManager.getInstance().getHttpService()//
                .getCoupons(userInfo.getToken(), pageInfo)//
                .compose(new CommonTransformer<>())//
                .subscribe(httpResult -> {
                    if (httpResult.getCode() == 200) {
                        businessLogic(httpResult.getData(), refreshStatus);
                    } else if (httpResult.getCode() == 401) {
                        refreshToken(pageId, refreshStatus);
                    }
                }, throwable -> serviceError());
    }

    private void refreshToken(int pageId, int refreshStatus) {
        LoginApi.refreshToken(true, new RemoteApiCallBack<Boolean>() {
            @Override
            public void onSuccess(Boolean aBoolean) {
                initData(pageId, refreshStatus);
            }

            @Override
            public void onFail(int status, String message) {
                serviceError();
            }
        });
    }

    private void serviceError() {
        //异常时，传null
        cf0.notifyData(null, CouponsFragment.REFRESH, CouponsFragment.NET_ERROR);
        cf1.notifyData(null, CouponsFragment.REFRESH, CouponsFragment.NET_ERROR);
        cf2.notifyData(null, CouponsFragment.REFRESH, CouponsFragment.NET_ERROR);
    }


    private void businessLogic(CouponsData data, int refreshStatus) {
        ArrayList<ContentBean> al0 = new ArrayList<>();
        ArrayList<ContentBean> al1 = new ArrayList<>();
        ArrayList<ContentBean> al2 = new ArrayList<>();

        for (ContentBean item : data.userDiscountPage.content) {
            if (item.timeRemain <= 0) { //已过期
                if (item.discount.discountType == 1) { // 已过期卡券
                    al2.add(item);
                } else if (item.discount.discountType == 2) { //分享卡券
                    al1.add(item);
                }
            } else if (item.discountStatus == 0) { //0 未使用，
                al0.add(item);
            } else if (item.discountStatus == 1) { //1 已使用
                al1.add(item);
            }
        }
        cf0.notifyData(al0, refreshStatus, CouponsFragment.NET_SURE);
        cf1.notifyData(al1, refreshStatus, CouponsFragment.NET_SURE);
        cf2.notifyData(al2, refreshStatus, CouponsFragment.NET_SURE);
    }

    private void initListener() {
        findViewById(R.id.back).setOnClickListener(v -> finish());
    }


    @Override
    public void onRefresh(int refreshStatus) {

        if (refreshStatus == CouponsFragment.REFRESH) { //刷新数据
            initData(0, refreshStatus);
        } else if (refreshStatus == CouponsFragment.LOAD_MORE) {
            if (pageInfo != null) {
                initData(pageInfo.page++, refreshStatus);
            } else {
                initData(0, refreshStatus);
            }

        }

    }
}
